class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int n = nums.length;
        Arrays.sort(nums);
        int abs = Integer.MAX_VALUE;
        int ans = 0;
        for (int i = 0; i < n - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < n - 1; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int target0 = -nums[i] - nums[j] + target;
                int l = j + 1, r = n - 1;
                while (l <= r) {
                    int mid = (l + r) >> 1;
                    int sub = target0 - nums[mid];
                    if (Math.abs(sub) < abs) {
                        ans = nums[i] + nums[j] + nums[mid];
                        abs = Math.abs(sub);
                    }
                    if (sub < 0) {
                        r = mid - 1;
                    } else if (sub > 0) {
                        l = mid + 1;
                    } else {
                        return target;
                    }
                }
            }
        }
        return ans;
    }
}